package com.yanlight.util;

import javax.crypto.Cipher;
import javax.security.cert.X509Certificate;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.PublicKey;
import java.util.Base64;

public class WxEncryptUtil {

    private static final String TRANSFORMATION_PKCS1Padding = "RSA/ECB/PKCS1Padding";

    private static final String CIPHER_PROVIDER = "SunJCE";

    private static final String PUBLIC_KEY_FILENAME = "/Users/wang/Desktop/炎光科技/trade/微信秘钥/服务商/cert/test.pem";

    private static final String CHAR_ENCODING = "UTF-8";//固定值，无须修改

    private static String CERT_VALUE = null;


    private static byte[] encryptPkcs1padding(PublicKey publicKey, byte[] data) throws Exception {
        Cipher ci = Cipher.getInstance(TRANSFORMATION_PKCS1Padding, CIPHER_PROVIDER);
        ci.init(Cipher.ENCRYPT_MODE, publicKey);
        return ci.doFinal(data);
    }

    //加密后的秘文，使用base64编码方法
    private static String encodeBase64(byte[] bytes) throws Exception {
        return Base64.getEncoder().encodeToString(bytes);
    }

    public static String rsaEncrypt(String content) {
        if (content == null || content.isEmpty()) {
            return null;
        }

        try {
            final byte[] PublicKeyBytes;
            if (CERT_VALUE != null) {
                PublicKeyBytes = CERT_VALUE.getBytes();
            } else {
                PublicKeyBytes = Files.readAllBytes(Paths.get(PUBLIC_KEY_FILENAME));
            }

            X509Certificate certificate = X509Certificate.getInstance(PublicKeyBytes);
            PublicKey publicKey = certificate.getPublicKey();
            String result = encodeBase64(encryptPkcs1padding(publicKey, content.getBytes(CHAR_ENCODING)));
            return result;
        } catch (Exception e) {
            return content;
        }
    }


    public static void initCert(String cert) {
        CERT_VALUE = cert;
    }
}
